package com.collect.tanzania.zhiScene.zhiWidget.zhiAuditer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.view.TimePickerView;
import com.collect.tanzania.R;
import com.collect.tanzania.zhiUtils.StringUtil;
import com.collect.tanzania.zhiUtils.ZHICalendarUtil;

import org.jaaksi.pickerview.dialog.DefaultPickerDialog;
import org.jaaksi.pickerview.picker.TimePicker;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;

import java.text.SimpleDateFormat;
import java.util.Date;


public class ZHIAuditerDateSelect extends RelativeLayout {

    public final static String RANGE_START = "START";

    private final Context mContext;

    private final String mDateFormatType;

    private TextView tv_due_time_start;

    private ImageView iv_due_time_start_del;

    private String mStartDate;

    private TimePicker mTimePicker;

    private TimePickerView mTimePickerView;

    private ZHIAuditerMonthSelectListener mZHIAuditerMonthSelectListener;

    public boolean mOnlyShowDefaultValue = false;

    public ZHIAuditerDateSelect(Context context) {
        this(context, null);
    }

    public ZHIAuditerDateSelect(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("CustomViewStyleable")
    public ZHIAuditerDateSelect(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ZHIRangeDateSelect);
        mDateFormatType = ta.getString(R.styleable.ZHIRangeDateSelect_dateFormatType);
        ta.recycle();

        initView();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        View mView = View.inflate(mContext, R.layout.view_auditer_date_select, this);

        LinearLayout ll_due_time_start = mView.findViewById(R.id.ll_due_time_start);

        tv_due_time_start = mView.findViewById(R.id.tv_due_time_start);
        iv_due_time_start_del = mView.findViewById(R.id.iv_due_time_start_del);

        ll_due_time_start.setOnClickListener(v -> showTimeDialog(RANGE_START));

        iv_due_time_start_del.setOnClickListener(v -> {
            if (mOnlyShowDefaultValue) {
                return;
            }

            String startDate = StringUtil.safeString(tv_due_time_start.getText().toString().trim());
            if (startDate.equalsIgnoreCase(mContext.getString(R.string.start_date))) {
                showTimeDialog(RANGE_START);
            } else {
                reset();
            }
        });

//        initStartDate();
    }

    @SuppressLint("SimpleDateFormat")
    public void initTimePicker(String onStartDateFormatYyyyMmDdHhMmSs) {
        TimePicker.OnTimeSelectListener mTimeSelectListener = (picker, date) -> {
            try {
                updatePromisedDueTimeStart(false, date);

            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        Date gDate;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (TextUtils.isEmpty(onStartDateFormatYyyyMmDdHhMmSs)) {
                int year = ZHICalendarUtil.getYear();
                int mon = ZHICalendarUtil.getMonth();
                int day = ZHICalendarUtil.getDay();
                year -= 1;

                gDate = simpleDateFormat.parse(year + "-" + mon + "-" + day);
            } else {
                gDate = simpleDateFormat.parse(onStartDateFormatYyyyMmDdHhMmSs);
            }

            long curYearTimeMils = gDate.getTime();

            int year = ZHICalendarUtil.getYear();
            int mon = ZHICalendarUtil.getMonth();
            int day = ZHICalendarUtil.getDay();
            long nextYearTimeMils = simpleDateFormat.parse(year + "-" + mon + "-" + day).getTime();

            PickerView.sOutTextSize = 16;
            PickerView.sCenterTextSize = 18;
            PickerView.sCenterColor = mContext.getResources().getColor(R.color.theme_color_0);
            PickerView.sOutColor = Color.GRAY;

            DefaultCenterDecoration.sDefaultLineWidth = 1;
            DefaultCenterDecoration.sDefaultLineColor = mContext.getResources().getColor(R.color.theme_color_0);

            int dtype = TimePicker.TYPE_YEAR | TimePicker.TYPE_MONTH | TimePicker.TYPE_DAY;//(TimePicker.TYPE_MIXED_DATE | TimePicker.TYPE_HOUR | TimePicker.TYPE_MINUTE);
//        if (mDateFormatType.equalsIgnoreCase(ZHIRangeDateSelectClickListener.TYPE_DATE)) {
//            dtype = TimePicker.TYPE_DATE;
//        }

            mTimePicker = new TimePicker.Builder(mContext, dtype, mTimeSelectListener)
                    .setRangDate(curYearTimeMils, nextYearTimeMils)
                    .setInterceptor((pickerView, params) -> {
                        pickerView.setVisibleItemCount(5);

                        int gtype = (int) pickerView.getTag();
                        if (gtype == TimePicker.TYPE_MIXED_DATE ||
                                gtype == TimePicker.TYPE_HOUR ||
                                gtype == TimePicker.TYPE_MINUTE) {
                            pickerView.setIsCirculation(true);
                        }
                    })
                    .setFormatter(new TimePicker.DefaultFormatter() {
                        @Override
                        public CharSequence format(TimePicker picker, int type, int position, long num) {
                            if (type == TimePicker.TYPE_MIXED_DATE) {
                                return ZHICalendarUtil.getDateFormated(num);
                            } else if (type == TimePicker.TYPE_YEAR) {
                                return num + "";
                            } else if (type == TimePicker.TYPE_MONTH) {
                                return num + "";
                            } else if (type == TimePicker.TYPE_DAY) {
                                return num + "";
                            } else if (type == TimePicker.TYPE_HOUR) {
                                return num + "h";
                            } else if (type == TimePicker.TYPE_MINUTE) {
                                return num + "min";
                            }
                            return super.format(picker, type, position, num);
                        }
                    })
                    .create();

            DefaultPickerDialog dialog = (DefaultPickerDialog) mTimePicker.dialog();
            dialog.getTitleView().setText(mContext.getString(R.string.pls_select));

            TextView btnCancel = (TextView) dialog.getBtnCancel();
            btnCancel.setText(mContext.getString(R.string.cancel));
            btnCancel.setVisibility(GONE);

            TextView btnConfirm = (TextView) dialog.getBtnConfirm();
            btnConfirm.setText(mContext.getString(R.string.confirm));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public void initStartDate() {
//        int year = ZHICalendarUtil.getYear();
//        int mon = ZHICalendarUtil.getMonth();
//        String showDateFormat = (year + "-" + mon);
//        mStartDate = showDateFormat;
//
//        tv_due_time_start.setText(showDateFormat);
//        tv_due_time_start.setTextColor(mContext.getResources().getColor(R.color.theme_color_0));
//        iv_due_time_start_del.setImageResource(R.drawable.ic_124);
//    }

    public void updatePromisedDueTimeStart(boolean reset, Date date) {
        try {
            if (reset) {
                mStartDate = "";

                tv_due_time_start.setTextColor(mContext.getResources().getColor(R.color.theme_transparent_7));
                tv_due_time_start.setText(mContext.getString(R.string.start_date));
                iv_due_time_start_del.setImageResource(R.drawable.ic_125);

                if (mZHIAuditerMonthSelectListener != null) {
                    mZHIAuditerMonthSelectListener.onDateSelected(mStartDate);
                }

                return;
            }

            if (date == null) {
                return;
            }

            String dateFormat;
            dateFormat = ZHICalendarUtil.getDateFormated(date.getTime(), "yyyy-MM-dd");

            mStartDate = dateFormat;

            String showDateFormat = dateFormat;
            String[] splits = dateFormat.split(" ");
            if (splits.length > 1) {
                showDateFormat = splits[0] + "\n" + splits[1];
            }

            tv_due_time_start.setText(showDateFormat);
            tv_due_time_start.setTextColor(mContext.getResources().getColor(R.color.theme_color_0));
            iv_due_time_start_del.setImageResource(R.drawable.ic_124);

            if (mZHIAuditerMonthSelectListener != null) {
                mZHIAuditerMonthSelectListener.onDateSelected(mStartDate);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updatePromisedDueTimeStartFromDateFormat(boolean reset, String dateFormat) {
        try {
            if (reset) {
                mStartDate = "";

                tv_due_time_start.setTextColor(mContext.getResources().getColor(R.color.theme_transparent_7));
                tv_due_time_start.setText(mContext.getString(R.string.start_date));
                iv_due_time_start_del.setImageResource(R.drawable.ic_125);

                if (mZHIAuditerMonthSelectListener != null) {
                    mZHIAuditerMonthSelectListener.onDateSelected(mStartDate);
                }

                return;
            }

            if (TextUtils.isEmpty(dateFormat)) {
                return;
            }

            mStartDate = dateFormat;

            String showDateFormat = dateFormat;
            String[] splits = dateFormat.split(" ");
            if (splits.length > 1) {
                showDateFormat = splits[0] + "\n" + splits[1];
            }

            tv_due_time_start.setText(showDateFormat);
            tv_due_time_start.setTextColor(mContext.getResources().getColor(R.color.theme_color_0));
            iv_due_time_start_del.setImageResource(R.drawable.ic_124);

            if (mZHIAuditerMonthSelectListener != null) {
                mZHIAuditerMonthSelectListener.onDateSelected(mStartDate);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showTimeDialog(String rangeType) {
        try {
            if (mOnlyShowDefaultValue) {
                return;
            }

            if (mTimePicker == null) {
                initTimePicker(null);
            }

            //mTimePicker.setSelectedDate(1549349843000L);
            mTimePicker.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void reset() {
        updatePromisedDueTimeStart(true, null);
    }

    public String getStartDate() {
        return StringUtil.safeString(mStartDate);
    }

    @SuppressLint("SimpleDateFormat")
    public void setStartDate(String date) {
        if (TextUtils.isEmpty(date)) {
            reset();
        } else {
            updatePromisedDueTimeStartFromDateFormat(false, date);
        }
    }

    public void setDateItemClick(ZHIAuditerMonthSelectListener listener) {
        mZHIAuditerMonthSelectListener = listener;
    }

    public interface ZHIAuditerMonthSelectListener {
        void onDateSelected(String date);
    }
}
